package com.paomi.client.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.paomi.client.R;
import com.paomi.client.activity.onlineSeat.model.SeatBean;

import java.util.List;


/**
 * Created by pc on 2018/4/2.
 * 显示在线选座的选票列表
 */

public class PopupWindowView extends PopupWindow {
    private View parentView;
    private TextView area_tv;//显示那个区的控件
    private RecyclerView ticket_list;//显示选票列表信息
    private int popupWidth;
    private int popupHeight;
    private Context mcontext;
    private WebView webView;
    public Typeface iconfont;
    OnDeleteClickListener onDeleteClickListener;
    private List<SeatBean> list;
    public PopupWindowView(Context context , List<SeatBean> popBeans , WebView webViewone,OnDeleteClickListener onDeleteClickListener) {
        super(context);
        mcontext=context;
        iconfont = Typeface.createFromAsset(context.getAssets(), "iconfont.ttf");
        webView=webViewone;
        list=popBeans;
        this.onDeleteClickListener=onDeleteClickListener;
        initView(context);
        setPopConfig();
        initData(context,list);
    }

    /**
     * 初始化控件
     * @param context
     */
    private void initView(Context context){
        parentView = View.inflate(context, R.layout.popup_window_layout, null);
        area_tv=(TextView) parentView.findViewById(R.id.area_tv);
        ticket_list=(RecyclerView) parentView.findViewById(R.id.ticket_list);
        ticket_list.setLayoutManager(new LinearLayoutManager(context));
        setContentView(parentView);
    }

    /**
     * 设置数据
     * @param context
     * @param popBeans
     */
    private void initData(Context context, final List<SeatBean> popBeans) {
        //给ListView添加数据
        final PopListViewAdapter popListViewAdapter = new PopListViewAdapter(context,popBeans);
        ticket_list.setAdapter(popListViewAdapter);
        popListViewAdapter.OnItemClickListen(new OnItemClickListener() {
            @Override
            public void setOnItemClick(View view, int pos) {
                String seat_no=""+list.get(pos).getId();
                list.remove(pos);
                refreshData(""+seat_no);
                popListViewAdapter.notifyDataSetChanged();
            }
        });
    }
    /**
     * 与js交互
     */
    private void refreshData(String seat_no) {
        final String s = getJSString(seat_no);
        // 只需要将第一种方法的loadUrl()换成下面该方法即可
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl(s);
                    webView.evaluateJavascript(s, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            //此处为 js 返回的结果
                        }
                    });
                }});
            if(onDeleteClickListener!=null){
                onDeleteClickListener.setOnItemClick(webView,list);
            }
        }else{
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl(s);
                }});
            if(onDeleteClickListener!=null){
                onDeleteClickListener.setOnItemClick(webView,list);
            }
        }
    }

    /**
     * 删除购物车的js
     * @return
     */
    @JavascriptInterface
    private String getJSString(String seat_no) {
        String js = "";
//        js = "javascript:_openMark()";
        js = "javascript:_delIdSeat('" + seat_no + "')";
//        js = "javascript:webpackJsonp()";
        Log.e("js",js);
        return js;
    }

    /**
     * 配置弹出框信息
     */
    private void setPopConfig(){
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
//        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//        this.setHeight(600);
        this.setHeight(500);
        // 设置弹出窗体可点击
        this.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0xccffffff);
        this.setBackgroundDrawable(dw);
        this.setOutsideTouchable(true);// 设置外部触摸会关闭窗口

        //获取自身的长宽高
        parentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupHeight = parentView.getMeasuredHeight();
        popupWidth = parentView.getMeasuredWidth();
    }
    /**
     * 设置显示在v上方(以v的左边距为开始位置)
     * @param v
     */
    public void showUp(View v) {
        //获取需要在其上方显示的控件的位置信息
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        //在控件上方显示
        showAtLocation(v, Gravity.NO_GRAVITY, (location[0]) - popupWidth / 2, location[1] - popupHeight);
    }

    /**
     * 设置显示在v上方（以v的中心位置为开始位置）
     * @param v
     */
    public void showUp2(View v) {
        //获取需要在其上方显示的控件的位置信息
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        //在控件上方显示
        showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight-460);
//        showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, 600);
    }
    /**
     *
     * @param manager   true为横向，false为竖向
     * @param activity
     * @return
     */
    public static LinearLayoutManager getRecyclerViewManager(boolean manager, Context activity){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        if (manager){
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        }else{
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        }

        return linearLayoutManager;
    }

    public class PopListViewAdapter extends RecyclerView.Adapter<PopListViewAdapter.ViewHolder> {
        Context mcontext;
        List<SeatBean> mlist;
        OnItemClickListener onClickListener;

        public void OnItemClickListen(OnItemClickListener onClickListener) {
            this.onClickListener = onClickListener;
        }


        public PopListViewAdapter(Context context, List<SeatBean> list) {
            this.mcontext = context;
            this.mlist = list;
        }

        @Override
        public PopListViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new PopListViewAdapter.ViewHolder(LayoutInflater.from(mcontext).inflate(R.layout.popup_list_item, parent, false));
        }

        @Override
        public void onBindViewHolder(final PopListViewAdapter.ViewHolder holder, final int position) {
            SeatBean ticketItem= mlist.get(position);
            holder.show_price.setText(ticketItem.getPrice()+"元");
            holder.show_location.setText(ticketItem.getRow()+"排"+ticketItem.getColumns()+"号");
            holder.show_area.setText(ticketItem.getSectionId()+"区");
            changeColor(holder.close_get,R.color.bar_grey,mcontext.getResources().getString(R.string.tip_close));

            holder.close_get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(onClickListener!=null){
                        notifyDataSetChanged();
                        onClickListener.setOnItemClick(holder.close_get,position);
                    }
                }
            });
        }
        private void changeColor(TextView iv, int color, String iv_icon) {
            iv.setText(iv_icon);
            iv.setTextColor(mcontext.getResources().getColor(color));
            iv.setTypeface(iconfont);
        }

        @Override
        public int getItemCount() {
            return mlist.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView show_price;//票价
            TextView show_location;//座位
            TextView show_area;//区域
            TextView close_get;//区域

            public ViewHolder(View itemView) {
                super(itemView);
                close_get = (TextView) itemView.findViewById(R.id.close_get);
                show_price = (TextView) itemView.findViewById(R.id.show_price);
                show_location = (TextView) itemView.findViewById(R.id.show_location);
                show_area = (TextView) itemView.findViewById(R.id.show_area);
            }
        }

    }
    public interface OnItemClickListener {
        void setOnItemClick(View view, int pos);
    }
    public interface OnDeleteClickListener {
        void setOnItemClick(View view, List<SeatBean> pos);
    }
}
